package cn.org.donald.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.org.donald.framework.pojo.dto.LoginUser;
import cn.org.donald.framework.util.BeanUtil;
import cn.org.donald.framework.util.RequestUtil;
import cn.org.donald.pojo.entity.Login;
import cn.org.donald.mapper.LoginMapper;
import cn.org.donald.framework.service.SysLoginService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Donald
 * @since 2020-11-16
 */
@Service
public class SysLoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements SysLoginService {

    @Autowired
    private LoginMapper loginMapper;


    /**
     * 保存用户登录信息
     * @param loginUser
     * @param request
     * @return
     */
    @Override
    public boolean saveLoginInfo(LoginUser loginUser, HttpServletRequest request) {
        String nowIp = RequestUtil.getRealIp(request);

        QueryWrapper<Login> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",loginUser.getUserId());
        Login login = loginMapper.selectOne(queryWrapper);

        Login insertLogin = new Login();
        insertLogin.setUserId(loginUser.getUserId());
        insertLogin.setIpLogin(nowIp);

        if (BeanUtil.isEmptyOrClassFieldAllEmpty(login)){
            int insert = loginMapper.insert(insertLogin);
            return insert > 0;
        }
        insertLogin.setGmtLastLogin(login.getGmtModified());
        insertLogin.setIpLastLogin(login.getIpLogin());
        insertLogin.setId(login.getId());
        int i = loginMapper.updateById(insertLogin);
        return i > 0;
    }
}
